#ifndef SPHEREH
#define SPHEREH

#include "hitable.h"
//球体类继承自hitable
class sphere : public hitable
{
public:
    vec3 center;
    float radius;
    //构造函数
    sphere(){}
    sphere(vec3 cen, float r) : center(cen), radius(r) {};
    //接受一个光线，判断出和自己的交点
    virtual bool hit(const ray& r, float tmin, float tmax, hit_record& rec) const
    {
        //含有一个未知数的向量，表示射线r到球心的距离
        vec3 oc = r.origin() - center;
        //球与射线相交方程dot(A-C)<R^2的化简结果是t^2·B^2+2t(A-C)·B+(A-C)^2-R^2=0,符合ax^2+bx+c形式
        //方程的a=B^2 b=2(A-C)·B c=(A-C)^2-R^2
        float a = dot(r.direction(), r.direction());
        float b = dot(oc, r.direction());
        float c = dot(oc, oc) - radius*radius;
        float discriminant = b*b - a*c;
        if (discriminant > 0)
        {
            //ох©╢╫Э╦Ы
            float temp = (-b - sqrt(b*b - a*c)) / a;
            if (temp < tmax && temp>tmin)
            {
                rec.t = temp;
                rec.p = r.point_at_parameter(rec.t);
                rec.normal = (rec.p - center) / radius;
                return true;
            }
            temp = (-b + sqrt(b*b - a*c)) / a;
            if (temp<tmax && temp>tmin)
            {
                rec.t = temp;
                rec.p = r.point_at_parameter(rec.t);
                rec.normal = (rec.p - center) / radius;
                return true;
            }
        }

        return false;
    }


};


#endif
